<?php

/**
 * Created by PhpStorm.
 * User: DRG
 * Date: 2018/3/30
 * Time: 21:18
 */

//创建server
//$server = new swoole_websocket_server('0.0.0.0',9502);
$message = new Message('0.0.0.0',9502);

class Message {
    public $server;

    public function __construct($ip, $port, $worker_num = 3,$deamonize = true){
            //创建server 对象 独立的服务器
        $this->server = new swoole_websocket_server($ip, $port);

        $this->server->set(array(
            'worker_num'=> $worker_num,
            'seamonie'  => $deamonize,//是否守护进程
        ));
    }

    //开启
    public function start(){
        //客户端与服务端建立连接
        $this->server->on('Opne',function ($server, $req){

        });
        //当服务器接收到客户端发来的消息
        $this->server->on('Message',function ($server, $frame){
            $msg = "{$frame->data}";
            $name = explode(':', $msg);
            if($name[0] = 'name'){
                $num = '欢迎'. $name[1] .'进入聊天室，当前在线人数'. count($server->connecttion_list()).'人';
                //客户端的连接id
                $server->push($frame->fd, $num);
            }else{
                foreach ($server->connecttion_list() as $fd){
                    $server->push($fd, $frame->data);
                }
            }
        });

        //关闭连接
        $this->server->on("Close", function ($server, $fd){

        });
        //
        $this->server->start();
    }
}